define(function (){

	var SSH2_TELNET = ['ORACLE']
	var SSH2_TELNET_SNMP = ['LINUX']
	var WMI_SNMP = ['WINDOWS']
	var SNMP = ['NETEYE_FIREWALL' ,'NE_HUAWEI' ,'H3C']
	var NO_CERT = ['MYSQL','COMMON_URL','TOMCAT','NGINX','PORT_MONITOR','APACHE','SQLSERVER']
	var MUST_CONFIG = ['LINUX','NETEYE_FIREWALL','WINDOWS','NE_HUAWEI','H3C']

	var el
	var el_cert_type_radio
	var el_cert_type_val

	var el_cert_type_div

	var el_current_cert_type

	var tmp_monitorTypeId
	var tmp_assetId
	var tmp_assetIp
	var tmp_monitorAgent

	var tmp_initData

	return {
		init : function (cEl ,monitorTypeId ,assetId ,assetIp  ,monitorAgent ,initData){
			var self = this
			tmp_monitorTypeId = monitorTypeId
			tmp_assetId = assetId
			tmp_assetIp = assetIp
			tmp_monitorAgent = monitorAgent
			tmp_initData = initData
			el = cEl
			um_ajax_html({
				url : "js/plugin/monitor/monitor_cert.html",
				selector : "#cert_div",
				successCallBack : function (data){
					el.html(data.html())
					el_cert_type_radio = el.find("[name=cert_type]")

					if (_.contains(NO_CERT ,tmp_monitorTypeId)){
						cEl.children().hide()
						cEl.append('<div style="height:150px;line-height:150px">本页没有配置项，请转到下一页！</div>')
						return false
					}

					self.__cert_switch_click_init()
					
					self.__cert_test_click_init()

					initData && self.__cert_type_click_init()
					self.__init_data_render(initData)

					index_form_init(el)
					g_validate.init(el)

					var cert_div_str

					if (_.contains(SSH2_TELNET ,tmp_monitorTypeId))
						cert_div_str = "SSH2_TELNET"
					if (_.contains(SSH2_TELNET_SNMP ,tmp_monitorTypeId))
						cert_div_str = "SSH2_TELNET_SNMP"
					if (_.contains(WMI_SNMP ,tmp_monitorTypeId))
						cert_div_str = "WMI_SNMP"
					if (_.contains(SNMP ,tmp_monitorTypeId))
						cert_div_str = "SNMP"
					

					var cert_div_array = cert_div_str.split("_")
					for (var i = 0; i < cert_div_array.length; i++) {
						el.find("[txt="+cert_div_array[i]+"]").addClass("dib").removeClass("dn")
					}

					!initData && self.__cert_type_click_init()
				}
			})
		},
		// 是否启用点击事件初始化
		__cert_switch_click_init : function (){
			el_cert_type_div = el.find("[data-name=cert_type_div]")
			// 判断监控器是否必须配置凭证
			if (_.contains(MUST_CONFIG ,tmp_monitorTypeId)){
				el.find("#cert_config_chk_div").hide()
				el.find("[data-name=open]").click()
				return false
			}
			el.find("[data-name=open]").click(function (){
				if ($(this).prop("checked"))
					g_mask.maskRemove(el_cert_type_div)
				else
					g_mask.mask(el_cert_type_div),g_validate.reset(el_current_cert_type)
			})
			g_mask.mask(el_cert_type_div)
			if (tmp_initData && tmp_initData.scCmd != "-1"){
				el.find("[data-name=open]").click()
			}
		},
		// 配置类型点击事件初始化
		__cert_type_click_init : function (){
			el_cert_type_radio.click(function (){
				el_cert_type_val = $(this).val()
				el.find("[data-target]").hide()
				if (el_current_cert_type)
					g_validate.reset(el_current_cert_type)
				el_current_cert_type = el.find("[data-target="+el_cert_type_val+"]")
				el_current_cert_type.show()
				__tpl_init()
			})
			el.find("[name=cert_type]:visible").eq(0).click()
		},
		// 测试按钮点击初始化
		__cert_test_click_init : function (){
			el.find("#cert_test_btn").click(function (){
				__certTest()
			})
		},
		__init_data_render : function (initData){
			console.log(initData)
			if (!initData)
				return false
			if (initData.scCmd == "-1")
				return false
			if (tmp_monitorTypeId == "ORACLE")
			{
				el.find("[name=cert_type][value="+initData.scCmd+"]").click()
				el_current_cert_type.umDataBind("render" ,initData)
				initData.trustName && el_current_cert_type.find("[data-id=monitorUserName]").val(initData.trustName)
				initData.trustPassWord && el_current_cert_type.find("[data-id=monitorPassWord]").val(initData.trustPassWord)
				initData.consolePort && el_current_cert_type.find("[data-id=monitorPort]").val(initData.consolePort)
			}
			else
			{
				if (initData.connectType == "SNMP"){
					el.find("[name=cert_type][value="+initData.connectType+"]").click()
					el_current_cert_type.umDataBind("render" ,initData.snmpList[0])
				}
				else if (tmp_monitorTypeId == "NE_HUAWEI"
							|| tmp_monitorTypeId == "H3C"){
					el.find("[name=cert_type][value=SNMP]").click()
					el_current_cert_type.umDataBind("render" ,initData.snmpList[0])
				}
				else
				{
					el.find("[name=cert_type][value="+initData.connectType+"]").click()
					el_current_cert_type.umDataBind("render" ,initData)
				}
			}
		},
		get_cert_type : function (){
			if (!el.find("[data-name=open]").prop("checked"))
				return "-1"
			return el.find("[name=cert_type]:checked").val()
		},
		validate : function (){
			if (!el.find("[data-name=open]").prop("checked"))
				return true
			if (el_cert_type_val == "SNMP"){
				return g_validate.validate(el_current_cert_type.find("[data-getter]:visible"))
			}
			if (!g_validate.validate(el_current_cert_type))
				return false
			else
				return true
		},
		save : function (){
			var certStore = [];
			if (!el.find("[data-name=open]").prop("checked")){
				certStore.push({scCmd : "-1"})
				return certStore
			}

			if (el_cert_type_val == "SSH2" || el_cert_type_val == "TELNET" || el_cert_type_val == "WMI") {
				certStore.push(el_current_cert_type.umDataBind("serialize"))
			}
			else if (el_cert_type_val == "SNMP") {
				certStore.push({snmpVo : el_current_cert_type.umDataBind("serialize")})
				certStore[0].snmpVo.edId = tmp_assetId
				certStore[0] = $.extend(certStore[0] ,certStore[0].snmpVo)
			}
			certStore[0].scCmd = el_cert_type_val
			certStore[0].edId = tmp_assetId
			certStore[0].consoleIp = el_cert_type_val
			certStore[0].connectType = el_cert_type_val

			certStore[0].trustName = certStore[0].monitorUserName
			certStore[0].trustPassWord = certStore[0].monitorPassWord
			certStore[0].consolePort = certStore[0].monitorPort
			return certStore
		}
	}

//模板初始化
function __tpl_init(){	
	if (el_cert_type_val == "SNMP") {
		var snmpMap = new HashMap();

		var snmpVer = el.find("[data-id=snmpVersion]");

		if (snmpVer.data("init") == "1")
			return false

		var snmpv1 = el.find("[data-getter=v1]");
		var snmpv2 = el.find("[data-getter=v2]");
		var snmpv3 = el.find("[data-getter=v3]");

		var authWay = el.find("[data-id=authWay]");
		var authPwd = el.find("[data-id=authPwd]");
		var encryptionWay = el.find("[data-id=encryptionWay]");
		var encryptionPwd = el.find("[data-id=encryptionPwd]");
		
		snmpVer.change(function(){
			if($(this).val()=="")
			{
				snmpv1.hide();
				snmpv2.hide();
				snmpv3.hide();
			}
			if($(this).val()=="1")
			{
				snmpv1.show();
				snmpv2.hide();
				snmpv3.hide();
			} 
			if($(this).val()=="2") 
			{
				snmpv1.hide();
				snmpv2.show();
				snmpv3.hide();
			}
			if($(this).val()=="3") 
			{
				snmpv1.hide();
				snmpv2.hide();
				snmpv3.show();
			}
		});
		snmpVer.trigger("change");

		el.find("[data-id=securityLevel]").change(function(){
			if($(this).val() == '1'){
				authWay.attr("disabled" ,"disabled");
				authPwd.val('');
				authPwd.attr("disabled" ,"disabled");
				encryptionWay.attr("disabled" ,"disabled");
				encryptionPwd.val('');
				encryptionPwd.attr("disabled" ,"disabled");
			}else if($(this).val() == '2'){
				authWay.removeAttr("disabled");
				authPwd.removeAttr("disabled");
				encryptionWay.attr("disabled" ,"disabled");
				encryptionPwd.val('');
				encryptionPwd.attr("disabled" ,"disabled");
			}else if($(this).val() == '3'){
				authWay.removeAttr("disabled");
				authPwd.removeAttr("disabled");
				encryptionWay.removeAttr("disabled");
				encryptionPwd.removeAttr("disabled");
			}else if($(this).val() == '-1'){
				authWay.attr("disabled" ,"disabled");
				authPwd.val('');
				authWay.val("-1");
				authPwd.attr("disabled" ,"disabled");
				encryptionWay.attr("disabled" ,"disabled");
				encryptionPwd.val('');
				encryptionWay.val("-1");
				encryptionPwd.attr("disabled" ,"disabled");
				authWay.trigger("change");
				encryptionWay.trigger("change");
			}
		});

		el.find("[data-id=securityLevel]").trigger("change");

		authWay.change(function (){
			if($(this).val()== '-1'){
				authPwd.val('');
				authPwd.attr("disabled" ,"disabled");
			}else {
				authPwd.removeAttr("disabled");
			}
		});

		encryptionWay.change(function (){
			if($(this).val()== '-1'){
				encryptionPwd.val('');
				encryptionPwd.attr("disabled" ,"disabled");
			}else {
				encryptionPwd.removeAttr("disabled");
			}
		});

		um_ajax_get({
	    	url: "rpc/getCodeList",
	    	isLoad: false,
	    	paramObj : {key:"snmpCodelist"},
	    	successCallBack:function (data){
	    		var data1 = data.snmpCodelist;
	    		for (var i = 0; i < data1.length; i++) {
	    			data1[i].id = data1[i].codevalue;
	    			data1[i].text = data1[i].codename;
	    			snmpMap.put(data1[i].id ,data1[i]);
	    		}
	    		data1.insert(0 ,{id:"-1",text:"---"});
	    		$("[data-id=snmpName]").select2({
	    			data:data1,width:"100%"
	    		});

	    		__initSnmpEvent(snmpMap);
	    	}
	    });

	    snmpVer.data("init" ,"1")
	}
}

// 通用：凭证信息表单的disabled属性增删
function dis(el) 
{
	/** arguments: 
		* 1.[el]：目标父节点元素,必填参数，dom对象或数组
		* 2.[type]：目标节点类型,选填参数，字符串或数组，默认为input
		* 3.r(reverse)：属性开关, 默认false为添加disabled属性
		**/
	var a = arguments;
	0===a.length && console.log("ERROR: dis(el,[type,r]) 参数缺失.");
	var el=(a[0].constructor!=Array) ? [el] : el,type=["input"],r=false;
	if (2 === a.length) 
	{
		if ("boolean" === typeof a[1]) 
		{
			r = a[1];
		} 
		else 
		{
			type = (Array != a[1].constructor) ? [a[1]] : a[1];
		}
	}
	if (3 === a.length) 
	{
		type = Array != a[1].constructor ? [a[1]] : a[1];
		r = a[2];
	}
	for (var i = 0; i < el.length; i++) {
		for (var j = 0; j < type.length; j++) {
			el[i].find(type[j]) && (r ? el[i].find(type[j]).removeAttr("disabled") : el[i].find(type[j]).attr("disabled","disabled"));
		}
	}
}

//凭证信息测试
function __certTest() 
{
	/**
	* arguments:
	* 1.dom: 被测div
	* 2.type: 凭证类型 ssh,telnet,snmp
	* 3.correct(){}: 参数矫正
	**/
	var url={
			"SSH2":"AssetOperation/doTestSsh",
			"TELNET":"AssetOperation/doTestTelnet",
			"SNMP":"AssetOperation/doTestSnmp",
			"WMI":"AssetOperation/doTestWmi"
		};

	var paramObj = el_current_cert_type.umDataBind("serialize");
	paramObj.snmpWCommunity = paramObj.writeCommunity || "";

	paramObj.monitorAgentId = tmp_monitorAgent
	paramObj.test_ip = tmp_assetIp

	um_ajax_post({
		url : url[el_cert_type_val],
		paramObj : paramObj,
		maskObj : "body",
		successCallBack : function (data){
			g_dialog.dialog('<div class="p10" id="test_alert"></div>' ,{
				width : "400px",
				title : "测试结果",
				isDetail : true,
				init : function(el){
					el.find("[id=test_alert]").html(data && data);
				}
			});
		}
	});
}

//snmp初始化
function __initSnmpEvent(snmpMap){
	$("[data-id=snmpName]").change(function (){
		if ($(this).val() != "-1"){
			var obj = snmpMap.get($(this).val());
			el.find("[data-id=snmpVersion]").val(obj.snmpVersion);
			el.find("[data-id=snmpVersion]").trigger("change");
			el.find("[id=snmp_info]").umDataBind("render" ,obj);
		}
	});
}

})